package com.meilai.project.interceptor;

import com.alibaba.fastjson.JSON;
import com.meilai.project.dto.CommonResult;
import com.meilai.project.mapper.system.UserMapper;
import com.meilai.project.util.JwtTokenUtil;
import com.meilai.project.util.ThreadLocalUserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WebInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebInterceptor.class);

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserMapper userMapper;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handlerMethod) throws Exception {

        String uri = request.getRequestURI();
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        // 过滤掉不需要加密的登录接口
        if (uri.startsWith("/api/web/login/sign-in")) {
            return true;
        }

        if (handlerMethod instanceof HandlerMethod) {
            HandlerMethod handler = (HandlerMethod) handlerMethod;
            NoAuth uncheckLogin = handler.getMethodAnnotation(NoAuth.class);
            if (uncheckLogin != null) {
                return true;
            }
            Class<?> beanClass = handler.getBeanType();
            if (beanClass.isAnnotationPresent(NoAuth.class)) {
                return true;
            }
        }

        String token = request.getHeader(tokenHeader);
        if (token == null) {
            error(response, "请传入token");
            return false;
        }

        String authTokenType = token.split(" ")[0];
        String authToken = token.split(" ")[1];

        String[] id_tenantName = jwtTokenUtil.getContentFromToken(authToken).toString().split(",");

        long id = Long.parseLong(id_tenantName[0]);
        if (id == 0) {
            error(response, "未找到您的信息");
            return false;
        }

        // 存入本地线程
        ThreadLocalUserUtil.set(userMapper.getUserVOById(id));

        //解析出的用户id加入请求中
        request.setAttribute("tokenUserId", id);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ThreadLocalUserUtil.remove();
    }

    /**
     * 返回错误信息
     */
    public HttpServletResponse error(HttpServletResponse response, String message) throws Exception {
        //response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSON.toJSON(new CommonResult().validateFailed(message)));
        response.getWriter().flush();
        return response;
    }
}
